import 'dart:math' as math;

import 'package:animation_effect_demo/src/widget/slider.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

import '../base/christmas_light_style.dart';
import '../effects/base/base_effect.dart';
import '../effects/effect_template.dart';
import 'button.dart';
import 'dialog.dart';


class TemplateSettings extends StatelessWidget {
  final int? speed;
  final RangeArgument? speedRange;

  final int? angle;
  final RangeArgument? angleRange;

  final int? density;
  final RangeArgument? densityRange;

  final int? colorWidth;
  final RangeArgument? colorWidthRange;

  final RangeArgument? colorCountRange;
  final List<Color>? colorList;
  final bool enableEditColor;
  // final DynamicType? dynamicType;
  final SpeedOrientation? speedOrientation;

  final bool isFixedColorCount;

  final int? templateIndex;
  final List<List<Color>>? colorTemplateList;

  final ValueChanged<double>? onColorWidthChanged;
  final ValueChanged<int>? onAngleChanged;
  final ValueChanged<double>? onSpeedChanged;
  final ValueChanged<double>? onDensityChanged;
  final ValueChanged<int>? onRemoveTemplate;
  final ValueChanged<int>? onTemplateSelect;
  final ValueChanged<List<Color>>? onAddColor;
  final ValueChanged<SpeedOrientation>? onDirectionChanged;

  TemplateSettings(
      {this.speed,
      this.speedRange,
      this.angle,
      this.angleRange,
      this.density,
      this.densityRange,
      this.colorWidth,
      this.colorWidthRange,
      this.colorCountRange,
      this.colorList,
      this.enableEditColor = false,
      // this.dynamicType,
      // this.directionIndex,
      this.speedOrientation,
      this.templateIndex,
      this.colorTemplateList,
      this.onColorWidthChanged,
      this.onAngleChanged,
      this.onSpeedChanged,
      this.onDensityChanged,
      this.onRemoveTemplate,
      this.onTemplateSelect,
      this.onDirectionChanged,
      this.onAddColor,
      this.isFixedColorCount = false});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (colorWidthRange != null)
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '宽度:',
                      style: TextStyle(fontSize: 14),
                    ),
                    Text('${colorWidth ?? colorWidthRange!.defaultValue}',
                        style: TextStyle(fontSize: 14)),
                  ],
                ),
              ),
              SizedBox(
                height: 10,
              ),
              ChristmasLightSlider(
                min: colorWidthRange!.start.toDouble(),
                max: colorWidthRange!.end.toDouble(),
                value: colorWidth!.toDouble(),
                onChanged: onColorWidthChanged,
                onChangeEnd: onColorWidthChanged,
              ),
              SizedBox(
                height: 15,
              ),
            ],
          ),
        if (angleRange != null)
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '角度:',
                      style: TextStyle(fontSize: 14),
                    ),
                    Text('$angle º', style: TextStyle(fontSize: 14)),
                  ],
                ),
              ),
              SizedBox(
                height: 10,
              ),
              ChristmasLightSymmetrySlider(
                value: angle?.toDouble()??angleRange!.defaultValue.toDouble(),
                leftNum: angleRange!.start,
                rightNum: angleRange!.end,
                onChanged: (value) => onAngleChanged?.call(value.round()),
                onChangeEnd: (value) => onAngleChanged?.call(value.round()),
              ),
              SizedBox(
                height: 15,
              ),
            ],
          ),
        ///当前不是静态模板并且速度范围不为空时显示设置
        if (speedRange != null && speedOrientation == null)
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('速度:', style: TextStyle(fontSize: 14)),
                    Text('$speed', style: TextStyle(fontSize: 14)),
                  ],
                ),
              ),
              SizedBox(
                height: 10,
              ),
              ChristmasLightSlider(
                min: speedRange!.start.toDouble(),
                max: speedRange!.end.toDouble(),
                value: speed!.toDouble(),
                onChanged: onSpeedChanged,
                onChangeEnd: onSpeedChanged,
              ),
              SizedBox(
                height: 15,
              ),
            ],
          ),
        if (densityRange != null)
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('密度:', style: TextStyle(fontSize: 14)),
                    Text('$density', style: TextStyle(fontSize: 14)),
                  ],
                ),
              ),
              SizedBox(
                height: 10,
              ),
              ChristmasLightSlider(
                min: densityRange!.start.toDouble(),
                max: densityRange!.end.toDouble(),
                value: density!.toDouble(),
                onChanged: onDensityChanged,
                onChangeEnd: onDensityChanged,
              ),
              SizedBox(
                height: 15,
              ),
            ],
          ),
        if (colorTemplateList?.isNotEmpty ?? false)
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Row(
                  children: [
                    Text('颜色:', style: TextStyle(fontSize: 14)),
                  ],
                ),
              ),
              SizedBox(
                height: 6,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: SizedBox(
                    height: 60.0,
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      children: [
                        Row(
                          children: colorTemplateList!
                              .asMap()
                              .entries
                              .map((e) => Center(
                                    child: Container(
                                      margin: EdgeInsets.only(right: 20),
                                      width: 34,
                                      height: 34,
                                      child:
                                          ChristmasLightColorCombinationButton(
                                        isSelected: templateIndex == e.key,
                                        colors: e.value,
                                        onLongPress: () {
                                          showDialog(
                                              context: context,
                                              builder: (_) {
                                                return ChristmasLightDialog(
                                                  child: Text('删除颜色模板？'),
                                                  actions: [
                                                    TextButton(
                                                        onPressed: () =>
                                                            Navigator.of(
                                                                    context)
                                                                .pop(),
                                                        child: Text('取消')),
                                                    TextButton(
                                                        onPressed: () =>
                                                            Navigator.of(
                                                                    context)
                                                                .pop(true),
                                                        child: Text('确定')),
                                                  ],
                                                );
                                              }).then((value) {
                                            if (value) {
                                              onRemoveTemplate?.call(e.key);
                                            }
                                          });
                                        },
                                        onPressed: () =>
                                            onTemplateSelect?.call(e.key),
                                      ),
                                    ),
                                  ))
                              .toList(),
                        ),
                        Center(
                            child: GestureDetector(
                          onTap: () async {
                            final ScrollController controller =
                                ScrollController();
                            int selectedIndex = 0;
                            int colorCount = colorList!.length;
                            var newColorList = List.generate(
                                colorCount,
                                (index) => Color.fromARGB(
                                    255,
                                    math.Random().nextInt(255),
                                    math.Random().nextInt(255),
                                    math.Random().nextInt(255)));
                            var result = await showDialog(
                                context: context,
                                builder: (context) {
                                  return ChristmasLightDialog(
                                    actions: [
                                      TextButton(onPressed: ()=> Navigator.of(context).pop(), child: Text('取消',style: TextStyle(color: Colors.grey),)),
                                      TextButton(onPressed: ()=> Navigator.of(context).pop(newColorList), child: Text('确定',style: TextStyle(color: christmasLightStyle.primaryColor),))
                                    ],
                                    child: StatefulBuilder(builder:
                                        (BuildContext context,
                                            StateSetter setState) {
                                      return Padding(
                                        padding:
                                        const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Text(
                                              '创建新的调色板',
                                              style: TextStyle(fontSize: 14),
                                            ),
                                            SizedBox(
                                              height: 10,
                                            ),
                                            SizedBox(
                                                height: 60.0,
                                                child: ListView(
                                                  scrollDirection:
                                                      Axis.horizontal,
                                                  controller: controller,
                                                  shrinkWrap: true,
                                                  children: [
                                                    Row(
                                                      children: newColorList
                                                          .asMap()
                                                          .entries
                                                          .map((e) => Center(
                                                                child:
                                                                    GestureDetector(
                                                                  onTap: () {
                                                                    setState(() {
                                                                      selectedIndex =
                                                                          e.key;
                                                                    });
                                                                  },
                                                                  onLongPress:
                                                                      isFixedColorCount
                                                                          ? null
                                                                          : () {
                                                                              showDialog(
                                                                                  context: context,
                                                                                  builder: (_) {
                                                                                    return ChristmasLightNormalDialog(
                                                                                      child: Text('确定删除该颜色吗？'),
                                                                                      onCancel: () => Navigator.of(context).pop(),
                                                                                      onConfirm: () => Navigator.of(context).pop(true),
                                                                                    );
                                                                                  }).then((value) {
                                                                                if (newColorList.length <= colorCountRange!.start) {
                                                                                  showToast('至少保留${colorCountRange!.start.toInt()}个颜色');
                                                                                  return;
                                                                                }
                                                                                if (value) {
                                                                                  setState(() {
                                                                                    newColorList.remove(e.value);
                                                                                    if (selectedIndex > newColorList.length - 1) {
                                                                                      selectedIndex = newColorList.length - 1;
                                                                                    }
                                                                                  });
                                                                                }
                                                                              });
                                                                            },
                                                                  child:
                                                                      Container(
                                                                    margin: EdgeInsets
                                                                        .only(
                                                                            right:
                                                                                20),
                                                                    decoration: BoxDecoration(
                                                                        border: Border.all(
                                                                            color: selectedIndex == e.key
                                                                                ? Colors.white
                                                                                : Colors.transparent),
                                                                        color: e.value),
                                                                    width: 34,
                                                                    height: 34,
                                                                  ),
                                                                ),
                                                              ))
                                                          .toList(),
                                                    ),
                                                    if (!isFixedColorCount)
                                                      Center(
                                                          child: GestureDetector(
                                                        onTap: () {
                                                          if (newColorList.length >=
                                                              colorCountRange!.end) {
                                                            showToast('已达到最大颜色数量');
                                                            return;
                                                          }
                                                          setState(() {
                                                            newColorList.add(newColorList[
                                                                selectedIndex]);
                                                            selectedIndex =
                                                                newColorList.length -
                                                                    1;
                                                          });
                                                          Future.delayed(
                                                              Duration(
                                                                  milliseconds:
                                                                      100), () {
                                                            controller.animateTo(
                                                                controller
                                                                    .position
                                                                    .maxScrollExtent,
                                                                duration: Duration(
                                                                    milliseconds:
                                                                        200),
                                                                curve: Curves
                                                                    .fastOutSlowIn);
                                                          });
                                                        },
                                                        child: Container(
                                                            width: 34,
                                                            height: 34,
                                                            decoration: BoxDecoration(
                                                                borderRadius:
                                                                    BorderRadius
                                                                        .circular(
                                                                            4.0),
                                                                border: Border.all(
                                                                    color: Colors
                                                                        .white
                                                                        .withAlpha(
                                                                            80))),
                                                            child:
                                                                Icon(Icons.add)),
                                                      ))
                                                  ],
                                                )),
                                            RGBSlider(
                                              color: newColorList[selectedIndex],
                                              onChanged: (color) => setState(() =>
                                              newColorList[selectedIndex] =
                                                      color),
                                              onChangeEnd: (color) => setState(
                                                  () => newColorList[selectedIndex] =
                                                      color),
                                            )
                                          ],
                                        ),
                                      );
                                    }),
                                  );
                                });

                            onAddColor?.call(result);

                            // var colorList = await ctx.dispatch(
                            //     EditTemplateBizActionCreator.onAddColorClick());
                            // if (colorList != null) {
                            //   // var list = ctx.state.colorTemplateList!.toList();
                            //   // list.add(colorList);
                            //   setState(() {
                            //     colorTemplateList!.add(colorList);
                            //   });
                            //   ctx.dispatch(EditTemplateBizActionCreator
                            //       .onUpdateColorTemplateList(
                            //           colorTemplateList!));
                            // }
                          },
                          child: Container(
                              width: 34,
                              height: 34,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(4.0),
                                  border: Border.all(
                                      color: Colors.white.withAlpha(80))),
                              child: Icon(Icons.add)),
                        ))
                      ],
                    )),
              )
            ],
          ),
        if(speedOrientation != null)
          Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: ()=> onDirectionChanged?.call(SpeedOrientation.vertical),
                      child: Padding(
                        padding: EdgeInsets.symmetric(vertical: 24.0),
                        child: Text(
                          '垂直',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: speedOrientation == SpeedOrientation.vertical
                                  ? christmasLightStyle.primaryColor
                                  : Color(0xFF7D8195)),
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: ()=> onDirectionChanged?.call(SpeedOrientation.horizontal),
                      child: Padding(
                        padding: EdgeInsets.symmetric(vertical: 24.0),
                        child: Text(
                          '水平',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: speedOrientation == SpeedOrientation.horizontal
                                  ? christmasLightStyle.primaryColor
                                  : Color(0xFF7D8195)),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              ChristmasLightSymmetrySlider(
                value: speed?.toDouble()??0,
                leftNum: -9,
                rightNum: 9,
                onChanged: (value) {
                  onSpeedChanged?.call(value);
                },
              )
            ],
          )
        // if (dynamicType != null)
        //   Column(
        //     children: [
        //       Row(
        //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //         children: [
        //           Text('水平:', style: TextStyle(fontSize: 14)),
        //           Text('${horizontalSpeed.abs()}',
        //               style: TextStyle(fontSize: 14)),
        //         ],
        //       ),
        //       ChristmasLightSymmetrySlider(
        //         value: horizontalSpeed * 10,
        //         leftNum: -100,
        //         rightNum: 100,
        //         onChanged: (value) =>
        //             setState(() => horizontalSpeed = value ~/ 10),
        //         onChangeEnd: (value) => setState(() {
        //           verticalSpeed = 0;
        //           horizontalSpeed = value ~/ 10;
        //         }),
        //       )
        //     ],
        //   ),
        // if (widget.dynamicType != null)
        //   Column(
        //     children: [
        //       Row(
        //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //         children: [
        //           Text('垂直:', style: TextStyle(fontSize: 14)),
        //           Text('${verticalSpeed.abs()}',
        //               style: TextStyle(fontSize: 14)),
        //         ],
        //       ),
        //       ChristmasLightSymmetrySlider(
        //         value: verticalSpeed * 10,
        //         leftNum: -100,
        //         rightNum: 100,
        //         onChanged: (value) =>
        //             setState(() => verticalSpeed = value ~/ 10),
        //         onChangeEnd: (value) => setState(() {
        //           horizontalSpeed = 0;
        //           verticalSpeed = value ~/ 10;
        //         }),
        //       )
        //     ],
        //   )
      ],
    );
    ;
  }
}
